<template>
	<div>
		<div class="container">
			<a-layout>
				<!--
				<a-layout-sider v-model:collapsed="collapsed" collapsed-width="60" width="400" theme="light" :collapsible="false">
				-->
				<a-layout-sider width="400" theme="light">
					<div class="pe-4">
						<a-category title="物资分类" code="MATERIAL_CATEGORY" :default-expand-all="false" :permission="{'create':141, 'update':142, 'delete':143}" @select="selectCategory" />
					</div>
				</a-layout-sider>

				<a-layout-content style="background:#fff">
					<div class="toolbar">
						<a-form ref="searchRef" :model="searchState" @finish="current=1;loading=true;initData()">
							<a-row :gutter="20">
								<a-col :span="6">
									<a-form-item label="名称">
										<a-input v-model:value="searchState.name" placeholder="请输入" allow-clear></a-input>
									</a-form-item>
								</a-col>
								<a-col :span="6">
									<a-form-item label="型号">
										<a-input v-model:value="searchState.model" placeholder="请输入" allow-clear></a-input>
									</a-form-item>
								</a-col>
								<a-col :span="6">
									<a-form-item label="单位">
										<a-input v-model:value="searchState.unit" placeholder="请输入" allow-clear></a-input>
									</a-form-item>
								</a-col>
								<a-col :span="6">
									<a-form-item label="状态">
										<a-select v-model:value="searchState.status" :options="statusOptions" option-filter-prop="label" allow-clear></a-select>
									</a-form-item>
								</a-col>
							</a-row>

							<!--
							<a-form-item label="物资编号">
								<a-input v-model:value="searchState.code" placeholder="请输入" allow-clear></a-input>
							</a-form-item>
							-->
							<a-form-item>
								<a-space>
									<a-button type="primary" html-type="submit">
										<search-outlined />搜索
									</a-button>

									<a-tooltip>
										<template #title>请先选择左侧物资类型</template>

										<a-button v-permission="93" :disabled="!currentDictionay.id" @click="addMaterial">
											<plus-outlined />添加
										</a-button>
									</a-tooltip>

									<a-upload v-if="currentDictionay.id && currentDictionay.is_leaf" v-permission="144" name="upload" :show-upload-list="false" :data="{ source_id: currentDictionay.id }" :action="`${baseURL}/material/import`" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="() => uploading = true" @change="uploading = false; initData()">
										<a-button>
											<template v-if="uploading">
												<loading-outlined />导入中...
											</template>
											<template v-else>
												<import-outlined />导入物资
											</template>
										</a-button>
									</a-upload>
									<a-button v-permission="144" type="link" @click="downloadTpl">
										<download-outlined />下载物资模板
									</a-button>
									<a-button v-permission="144" type="link" :disabled="!searchState.category_id" @click="exportAll">
										<download-outlined />导出
									</a-button>
									<a-button v-permission="95" danger :disabled="!selectedRowKeys.length" @click="deleteMaterial">
										<delete-outlined />删除物资
									</a-button>
									<a-button v-permission="215" :disabled="!selectedRowKeys.length" @click="changeMoreStatus(1)">批量启用</a-button>
									<a-button v-permission="215" :disabled="!selectedRowKeys.length" @click="changeMoreStatus(0)">批量禁用</a-button>
								</a-space>
							</a-form-item>
						</a-form>
					</div>

					<div class="mt-2">
						<h2 class="my-4">{{ [...currentDictionay.parents, {name: currentDictionay.name}].map((d) => d.name).join(' - ') }}</h2>

						<a-table :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: changeSelectedRowKeys }" :columns="columns" :scroll="tableScroll" row-key="id" :data-source="materialSource" :pagination="pagination" :loading="loading" @change="initData">
							<template #bodyCell="{ column, record }">
								<template v-if="column.key === 'operation'">
									<a-space>
										<a-button v-permission="94" type="link" @click="editMaterial(record)">
											<edit-outlined />修改
										</a-button>
										<a-button v-permission="95" type="link" style="color:#ff7875" @click="deleteMaterial(record.id)">
											<delete-outlined />删除
										</a-button>
									</a-space>
								</template>
								<template v-if="column.dataIndex === 'status'">
									<a-space>
										<a-switch v-model:checked="record.status" v-permission:show="'215'" checked-children="启用" un-checked-children="禁用" :checked-value="1" :un-checked-value="0" :loading="record.loading" @click="changeStatus(record)" />
									</a-space>
								</template>
							</template>
						</a-table>
					</div>

					<a-modal v-model:visible="visible" :width="400" :title="`${formState.id ? '修改' : '添加'}物资`" @ok="saveMaterial">
						<a-form ref="formRef" :model="formState" v-bind="{labelCol: { style: { width: '80px' } }}">
							<a-form-item label="物资名称" name="name" :rules="{required:true, message:'请输入物资名称'}">
								<a-input v-model:value="formState.name" disabled />
							</a-form-item>
							<!--
							<a-form-item label="物资编码" name="code" :rules="{required:true, message:'请输入物资编码'}">
								<a-input v-model:value="formState.code" />
							</a-form-item>
							-->
							<a-form-item label="规格型号" name="model" :rules="{required:true, message:'请输入规格型号'}">
								<a-input v-model:value="formState.model" />
							</a-form-item>
							<a-form-item label="属性" name="attr">
								<a-input v-model:value="formState.attr" />
							</a-form-item>

							<a-form-item label="计量单位" name="unit">
								<!--
								<a-input v-model:value="formState.unit" />
								

								<a-tree-select v-model:value="formState.unit" :show-search="true" placeholder="请选择计量单位" :field-names="{value:'label'}" allow-clear tree-default-expand-all :tree-data="unitOptions" tree-node-filter-prop="label">
									<template #title="{label}">{{ label }}</template>
								</a-tree-select>-->

								<a-select v-model:value="formState.unit" :show-search="true" placeholder="请选择计量单位" :field-names="{value:'label'}" :options="unitOptions" option-filter-prop="label" mode="multiple"></a-select>
							</a-form-item>
						</a-form>
					</a-modal>
				</a-layout-content>
			</a-layout>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, computed, getCurrentInstance, watch, toRaw } from "vue";
const { proxy } = getCurrentInstance();

import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons-vue";

import { ACategory } from "../components";

import { listToTree, post, postJson } from "../utils";

import { usePagination } from "vue-request";

const searchRef = ref();
const searchState = reactive({});
//collapsed
//const collapsed = ref(true);

const selectedRowKeys = ref([]);

const changeSelectedRowKeys = keys => {
	selectedRowKeys.value = keys;
};

const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left",
		fixed: "left"
	},
	{
		title: "物资名称",
		dataIndex: "name",
		sorter: false,
		width: 250,
		ellipsis: true
	},
	/*
	{
		title: "物资编号",
		dataIndex: "code",
		sorter: false,
		width: 160,
		ellipsis: true
	},
	*/
	{
		title: "规格型号",
		dataIndex: "model",
		sorter: false,
		width: 160,
		ellipsis: true
	},
	/*
	{
		title: "属性",
		dataIndex: "attr",
		sorter: false,
		width: 150,
		ellipsis: true
	},
	*/
	{
		title: "计量单位",
		dataIndex: "unit",
		sorter: false,
		width: 100,
		ellipsis: true
		/*
		customRender: ({ text, record, index, column }) => {
			const item = (unitOptions.value || []).find(item => parseInt(item.id) === parseInt(text));
			return item && item.name;
		}
		*/
	},
	{
		title: "状态",
		dataIndex: "status",
		width: 100,
		align: "center",
		fixed: "right"
	},
	{
		title: "操作",
		key: "operation",
		sorter: false,
		fixed: "right",
		width: 160,
		align: "center"
	}
];
const statusOptions = [
	{
		value: 1,
		label: "启用"
	},
	{
		value: 0,
		label: "禁用"
	}
];
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));

const { data, loading, run, current, pageSize, total } = usePagination(params => post("material", { ...params, ...searchState }), {
	defaultParams: [
		{
			page_size: 100
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});
const materialSource = computed(() => data.value?.data || []);

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value,
	showTotal() {
		return `共 ${total.value} 条`;
	}
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };

	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};

const visible = ref(false);

const addMaterial = () => {
	const { id, name, parent_id, is_leaf } = currentDictionay.value;
	if (!is_leaf) {
		proxy.$message.error("此内容为物资分类，不允许创建物资型号");

		return false;
	}
	formState.value = {
		name,
		category_id: parent_id,
		source_id: id,
		unit: []
	};

	visible.value = true;
};

const editMaterial = record => {
	//formState.value = { ...record, unit: record.unit.split(",") || [] };
	//record.unit = parseInt(record.unit);

	formState.value = { ...record, unit: record.unit?.split(",") || [] };
	visible.value = true;
};
const deleteMaterial = id => {
	if (typeof id === "object") id = selectedRowKeys.value.join(",");
	if (!id) {
		proxy.$message.error("请选择需要删除的物资");
		return;
	}

	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的物资吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("material/delete", { id })
				.then(() => {
					proxy.$message.success("物资删除成功");
					initData();
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		}
	});
};
const changeMoreStatus = status => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要批量${status === 1 ? "启用" : "禁用"}选中的物资吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("material/save/statuses", { ids: selectedRowKeys.value, status })
				.then(() => {
					proxy.$message.success("物资删除成功");
					selectedRowKeys.value = [];
					initData();
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		}
	});
};

const formRef = ref();
const formState = ref({});
const changeStatus = record => {
	record.loading = true;
	postJson("material/save", { id: record.id, status: record.status })
		.then(() => {
			proxy.$message.success("操作成功", 1).then(async () => {
				record.loading = false;
				initData();
			});
		})
		.catch(err => {
			proxy.$message.error(err);
			record.loading = false;
			initData();
		});
};

const saveMaterial = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();

			const params = { ...formState.value };
			params.unit = params.unit.join(",");
			post("material/save", params)
				.then(() => {
					proxy.$message.success("物资信息提交成功", 1);
					visible.value = false;

					initData();
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
};

watch(visible, value => {
	if (value) formRef.value?.clearValidate();
});

const currentDictionay = ref({
	parents: []
});

const selectCategory = e => {
	//parents重新排序
	const { parents, parent_ids } = e;

	e.parents = parent_ids
		.split(",")
		.map(id => {
			//const d = parents.find(v => v.id === parseInt(id));
			return Object.fromEntries(parents.map(d => [d.id.toString(), d]))[id] || null;
		})
		.filter(d => !!d);

	currentDictionay.value = e;
};

watch(currentDictionay, value => {
	searchState.category_id = value.id;
	initData();
});

const unitOptions = ref([]);
post("dictionary", { root_code: "MATERIAL_UNIT", page_size: 1000 }).then(data => {
	const { root_id: rootId } = data[0] || {};

	unitOptions.value = listToTree(data, rootId);
});

import { baseURL } from "../utils/request";
import { exportData } from "../utils/exportData.js";

const downloadTpl = () => {
	window.open(`${baseURL.replace("/api", "")}/uploadfile/tpl-material.xlsx`);
};

const exportAll = async () => {
	const { data } = await post("material/export", { ...searchState });
	const columns = [];
	const dataSource = [];
	columns.push({ title: "物料名称", dataIndex: "name" }, { title: "规格型号", dataIndex: "model" }, { title: "编号", dataIndex: "code" });
	data.forEach(item => {
		dataSource.push({ name: item.name, code: item.code, model: item.model });
	});
	exportData(columns, dataSource, `file.xlsx`);
};
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
:deep(.ant-layout-sider-trigger) {
	width: 60px;
	background-color: #1890ff;
	color: #fff;
}
</style>
